package com.idea.relax.mybatis.toolkit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.idea.relax.mybatis.page.PageReqVO;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Collection;

/**
 * @className: Condition
 * @description:
 * @author: salad
 * @date: 2021/11/10
 **/
public class Condition<T> {


	private QueryWrapper<T> getQueryWrapper() {
		return Wrappers.query();
	}

	public static <T> QueryWrapper<T> getQueryWrapper(T target, String... exclude) {
		return getQueryWrapper(target, false, exclude);
	}

	public static <T> QueryWrapper<T> getQueryWrapper(T target, boolean isEnhanceMode, String... exclude) {
		QueryWrapper<T> qw = new Condition<T>().getQueryWrapper();
		try {
			PropertyDescriptor[] propertyDescriptors = PropertyDescriptorUtil.getPropertyDescriptors(target);
			for (PropertyDescriptor proDesc : propertyDescriptors) {
				Method readMethod = proDesc.getReadMethod();
				Object value = readMethod.invoke(target);
				if (RelaxUtil.isEmpty(value) || FieldKeyword.exclude(proDesc.getName(), exclude)) {
					continue;
				}
				String fieldName = RelaxUtil.humpToUnderline(proDesc.getName());
				Class<?> propertyType = proDesc.getPropertyType();
				if (isEnhanceMode) {
					if (CharSequence.class.isAssignableFrom(propertyType)) {
						qw.like(fieldName, value);
					} else if (Collection.class.isAssignableFrom(propertyType) || propertyType.isArray()) {
						qw.in(fieldName, value);
					} else {
						qw.eq(fieldName, value);
					}
				} else {
					qw.eq(fieldName, value);
				}
			}
		} catch (Exception e) {
			throw RelaxUtil.unchecked(e);
		}
		return qw;
	}

	/**
	 * 转化成mybatis plus中的Page
	 *
	 * @param pageReqVO 分页VO
	 * @return IPage
	 */
	public static <T> IPage<T> getPage(PageReqVO pageReqVO) {
		Page<T> page = new Page<>(
			RelaxUtil.isEmpty(pageReqVO.getCurrent()) ? 0 : pageReqVO.getCurrent(),
			RelaxUtil.isEmpty(pageReqVO.getPageSize()) || pageReqVO.getPageSize() == 0 ? 10 : pageReqVO.getPageSize()
		);
		String[] ascArr = RelaxUtil.toArray(pageReqVO.getAscs(), ",");
		for (String asc : ascArr) {
			page.addOrder(OrderItem.asc(RelaxUtil.humpToUnderline(RelaxUtil.cleanIdentifier(asc))));
		}
		String[] descArr = RelaxUtil.toArray(pageReqVO.getDescs(), ",");
		for (String desc : descArr) {
			page.addOrder(OrderItem.desc(RelaxUtil.humpToUnderline(RelaxUtil.cleanIdentifier(desc))));
		}
		return page;
	}


}
